//获取应用实例
const app = getApp();

Page({
    data: {
      id:0,
      templateData:{}, // 选中的样板数据
      nav_active_index: 0,
      nav_list: [
          {id: 1, name: '买手完善',all:21,value:0},
          {id: 2, name: '商品完善',all:11,value:0},
          {id: 3, name: '通用属性',all:0,value:0},
      ],
      templateList:[], // 样板列表 
      is_show_temp: false,
      is_show_shade: false, 
      templateTotal: 0,
      templatePage: 0,
      goodsNOTag:false, // 货号开关 false-可填 true-禁止填
      templateKw: '',
      chooseTemplate: '',           // 已经选择的样板名称 
      time_cate_two:[],             // 二级时间分类-下拉需要的数据
      time_cate_all: [],            // 时间分类（波段）-原多级数据 
      style_cate:[], // 风格数据
      definition:[], // 产品定义 -下拉需要的数据
      color_list:[], // 颜色列表
      bd_list:[], // 波段下来数据
      style_item:[], // 一级风格
      sel_index:{
        time_cate:[0,0], // 二级时间分类-已选择的数据
        color:0,
        style_id:0,
        definition:[0,0], // 产品定义(二级风格)
        bd:[0,0,0], //波段
      },
      sel_text: {
        time_cate_name:'', // 二级时间分类
        color_name:'',// 颜色名
        definition:'', // 产品定义(二级风格)
        bd_name:'',// 颜色名
        style_name:'',// 一级风格 
      },  
        formData: {
            template_id: 0, 
            delivery_time:'',
            is_first: 0,
            time_cate_id:[],
            color_id:0,
            definition:[],
            cost:'',
            estimated_cost:'',
            sale_price:'',
            distribution_price:'', // 分销价格
            bd_id:[],
            style_id:0,
            gram_weight:'',
            template_type: '',
            thickness: '',
            age_name: '',
            faction_name: '',
            uneven_color:'',
            warm_color:'',
            color_system:'', 
            fabric: "", 
            lining: '',
            filler: '',
            shipping_remark: '',
            window_level_remark: '',
           
        }, 
        order_type_list: [], // 订单属性 - 远程
        thick_list: [], // 厚薄度- 远程
        pattern_list: [
            {id: 1, name:'合体', value: '合体'},
            {id: 2, name:'紧身', value: '紧身'},
            {id: 3, name:'宽松', value: '宽松'},
            {id: 4, name:'修身', value: '修身'},
        ],
        age_list:[{'name':'年轻'},{'name':'跨龄'},{'name':'成熟'}],
        faction_list:[{'name':'时尚'},{'name':'常规'},{'name':'经典'}],
        //深浅色 
        uneven_color_list:[{'name':'深色系'},{'name':'浅色系'}],
        warm_color_list:[{'name':'基础色系'},{'name':'冷色系'},{'name':'暖色系'}],
        color_system_list:[{'name':'黑色系'},{'name':'白色系'},{'name':'灰色系'}
        ,{'name':'蓝色系'},{'name':'绿色系'},{'name':'红色系'},{'name':'粉色系'}
        ,{'name':'紫色系'},{'name':'橙色系'},{'name':'黄色系'},{'name':'大地色系'}], 
        stockHeaders: [
          // "仓库",
          "28/44/160/37/S",
          "29/46/165/38/M",
          "30/48/170/39/L",
          "31/50/175/40/XL",
          "32/52/180/41/2XL",
          "33/54/185/42/3XL",
          "34/56/190/43/4XL",
          "35/58/195/44/5XL",
          "36/6XL",
          "38/7XL",
          "40",
          "42",
        ],
        stock_data:[],
        stock_field:[  // 注：仓库库存尺码对应字段，禁止乱改，必须与后台对应尺码关系一致
           'first',  
           'second',  
           'third',  
           'fourth',  
           'fifth', 
           'sixth', 
           'seventh',  
           'eighth', 
           'ninth',
           'tenth',
           'eleven',
           'twelve',
        ],
        buyerLabelArr:{
          template_id:false,
          color_id:false,
          goods_no:false,
          goods_number:false,
          entry_time:false,
          delivery_time:false,
          time_cate_id:false, 
          definition:false,
          cost:false,
          estimated_cost:false,
          sale_price:false,
          distribution_price:false,

          bd_id:false,
          style_id:false,
          gram_weight:false,
          template_type:false,
          thickness:false,
          age_name:false,
          faction_name:false,
          uneven_color:false,
        

        },
        goodsLabelArr:{
          bd_id:false,
          style_id:false,
          gram_weight:false,
          template_type:false,
          thickness:false,
          age_name:false,
          faction_name:false,
          uneven_color:false,
          warm_color:false,
          color_system:false,
          stock_data:false,
        } ,
          
         
    },
    onLoad: function (options) {
        // 设置标题
        wx.setNavigationBarTitle({
            title: '创建预生产计划'
        }); 
        this.itemData(); // 项数据
        this.get_time_cate(); // 获取时间分类
        this.get_color_list(); // 颜色列表
        this.get_style_list(); // 获取风格分类
        this.getTemplateList();
        
        // 如果是编辑的话
        if (options.id != undefined && options.id > 0) {
            // 重设标题
            wx.setNavigationBarTitle({
                title: '编辑预生产计划'
            });
            this.setData({
              id: options.id
            });
           
            // 获取样板详情
            this.get_detail();
           
        }else{
          this.addInit();
        }
    },
    // 切换选项卡
    ChangeNav: function (events) {
      var index = events.currentTarget.dataset.index;
      this.setData({
          nav_active_index: index
      });
    },
    // 内容值变动，计算完成项
    labelChange: function (changeKey,changeVal) { 
    
      // 根据key去判断
      let buyerArr = this.data.buyerLabelArr
      let goodsArr = this.data.goodsLabelArr
      let val = (changeVal == 0 || changeVal == '' || changeVal == null || changeVal == undefined)?false:true;

      if (changeKey in buyerArr) { 
        buyerArr[changeKey] = val
        this.setData({
          buyerLabelArr :  buyerArr,
        }); 
        console.log('元素存在',{changeKey:changeKey,buyerArr:buyerArr});  
      } else {  
        console.log('元素不存在',{changeKey:changeKey,buyerArr:buyerArr});  
      } 
      if (changeKey in goodsArr) {  
        console.log('元素存在',{changeKey:changeKey,goodsArr:goodsArr});   
        goodsArr[changeKey] = val
        this.setData({
          goodsLabelArr :  goodsArr,
        }); 
 
      } else {  
        console.log('元素不存在',{changeKey:changeKey,goodsArr:goodsArr});  
      } 
  
      this.calLabel();
    },

    calLabel: function () { 
      let nav_list = this.data.nav_list
      // 买手
      let buyerLabelNum = 0
      let buyerLabelArr = this.data.buyerLabelArr
      for (let key in buyerLabelArr) {
        if(buyerLabelArr[key]){
            buyerLabelNum++ 
        }
      }
      // 商品 
      let arr = this.data.goodsLabelArr
      let total = 0
      for (let key in arr) {
        if(arr[key]){
          total++
        }
      }
      nav_list[0]['value'] = buyerLabelNum
      nav_list[1]['value'] = total 
      this.setData({
        nav_list :  nav_list,
      }); 
    },
    // 统计仓库商品数量的值
    calStockTotal:function(stock_data){
      if(stock_data == null || stock_data == undefined || stock_data == '') return 0;
      let stockTotal = 0;
      for (let key in stock_data) {
         for (let k1 in stock_data[key]) {
             if(k1 != 'code' && k1 != 'name' ){
                 stockTotal   += Number(stock_data[key][k1])
             } 
         }
      }
      return stockTotal;
    }, 

    // 预览图片
    PreviewImg: function (events) {
      var pic_arr = events.currentTarget.dataset.pic;
      if (pic_arr.length == 0) {
          return false;
      }
      // 调用
      wx.previewImage({
          current: pic_arr[0],
          urls: pic_arr
      })
    },
    addInit: function () {
      let result = app.request_api('admin/PreProductPlan/addInit', { 
      }, true, 'GET');
      result.then(res => {  
          this.setData({ 
            stock_data: res.stock_data 
          }); 
      });
    },
    itemData: function () {
      let result = app.request_api('admin/PreProductPlan/item_data', { 
      }, true, 'GET');
      result.then(res => {  
          this.setData({ 
            order_type_list:res.order_type,
            thick_list:res.thick_list,
          }); 
      });
    },
    // 获取样板详情
    get_detail: function () {
        var result = app.request_api('admin/PreProductPlan/edit', {
            id: this.data.id
        }, true, 'GET');
        result.then(res => {
            let tempData = res.row   
            // 样板-标题（货号）
            let chooseTemplate = ''
            if(tempData.template){
              if(tempData.template.template_no){
                chooseTemplate = `${tempData.template.template_name}(${tempData.template.template_no}`
              }else{
                chooseTemplate = tempData.template.template_name
              }
            } 
            this.setData({   
              chooseTemplate: chooseTemplate,
              [`formData.template_id`]: tempData.template_id || 0,
              [`formData.color_id`]: tempData.color_id || 0,
              [`formData.goods_no`]: tempData.goods_no || '',
              [`formData.goods_number`]: tempData.goods_number || 0,
              [`formData.order_type`]: tempData.order_type || 0, 
              [`formData.entry_time`]: tempData.entry_time || '',
              [`formData.delivery_time`]: tempData.delivery_time || '', 
              [`formData.time_cate_id`]: tempData.time_cate_id || [], 
              [`formData.definition`]: tempData.definition || [],
               
              [`formData.cost`]: tempData.cost || 0,
              [`formData.estimated_cost`]: tempData.estimated_cost || 0,
              [`formData.cost`]: tempData.cost || 0,
              [`formData.sale_price`]: tempData.sale_price || 0,
              [`formData.distribution_price`]: tempData.distribution_price || 0,
              [`formData.bd_id`]: tempData.bd_id || [], 
              [`formData.style_id`]: tempData.style_id || 0,
              [`formData.gram_weight`]: tempData.gram_weight || 0,
              
              [`formData.template_type`]: tempData.template_type || '',
              [`formData.thickness`]: tempData.thickness || '',
              [`formData.age_name`]: tempData.age_name || '',
              [`formData.faction_name`]: tempData.faction_name || '',
              [`formData.uneven_color`]: tempData.uneven_color || '',
              [`formData.warm_color`]: tempData.warm_color || '', 
              [`formData.color_system`]: tempData.color_system || '',

              [`formData.similar`]: tempData.similar || '',
              [`formData.fabric`]: tempData.fabric || '',
              [`formData.lining`]: tempData.lining || '',
              [`formData.filler`]: tempData.filler || '',
              [`formData.shipping_remark`]: tempData.shipping_remark || '',
              [`formData.window_level_remark`]: tempData.window_level_remark || '',
              
              // 二级时间分类
              [`sel_text.time_cate_name`]: tempData.time_cate_name,
              // 颜色名
              [`sel_text.color_name`]: tempData.color_name,
              // 产品定义(二级风格)
              [`sel_text.definition`]: tempData.definition_name,
              // 颜色名
              [`sel_text.bd_name`]: tempData.bd_name,
              // 一级风格 
              [`sel_text.style_name`]:tempData.style_name,
              [`sel_text.order_type`]:tempData.order_type_name,
              
              stock_data:tempData.stock_data,
              templateData:tempData.template || [], 

            }); 
            this.initLabelItem(); // 必须在赋值之后调用
        });
    },
    
    // 初始化 统计项 （必须在赋值之后调用）
    initLabelItem: function() {
      let formData = this.data.formData 
     
      // 标签完成项统计
      let buyerLabelArr = {
        template_id:formData.template_id?true:false,
        color_id:formData.color_id?true:false,
        goods_no:formData.goods_no?true:false,
        goods_number:formData.goods_number?true:false,
        order_type:formData.order_type?true:false,
        entry_time:formData.entry_time?true:false,
        delivery_time:formData.delivery_time?true:false,
        time_cate_id:formData.time_cate_id && formData.time_cate_id.length>0?true:false,
        
        definition:formData.definition && formData.definition.length>0?true:false,
        cost:formData.cost>0?true:false,
        estimated_cost:formData.estimated_cost>0?true:false,
        sale_price:formData.sale_price>0?true:false,
        distribution_price:formData.distribution_price>0?true:false,
        
        // 重复部分
        bd_id:formData.bd_id && formData.bd_id.length>0?true:false,
        style_id:formData.style_id?true:false,
        gram_weight:formData.gram_weight>0?true:false,
        template_type:formData.template_type?true:false,
        thickness:formData.thickness?true:false,
        age_name:formData.age_name?true:false,
        faction_name:formData.faction_name?true:false,
        uneven_color:formData.uneven_color?true:false,
        
        // 重复部分 end
      }
      let goodsLabelArr = {
        bd_id:formData.bd_id && formData.bd_id.length>0?true:false,
        style_id:formData.style_id?true:false,
        gram_weight:formData.gram_weight>0?true:false,
        template_type:formData.template_type?true:false,
        thickness:formData.thickness?true:false,
        age_name:formData.age_name?true:false,
        faction_name:formData.faction_name?true:false,
        uneven_color:formData.uneven_color?true:false,
        warm_color:formData.warm_color?true:false,
        color_system:formData.color_system?true:false, 
        stock_data:false,
      } 
      let stockTotal = this.calStockTotal(this.data.stock_data);
      goodsLabelArr.stock_data = stockTotal>0?true:false 
      this.setData({  
        buyerLabelArr:buyerLabelArr,
        goodsLabelArr:goodsLabelArr, 
      })
      this.calLabel(); // 计算数量 
    }, 

    dTimeChange: function(e) {
      this.labelChange('delivery_time', e.detail.value) 
      this.setData({
        [`formData.delivery_time`]:  e.detail.value,  
      })
    }, 
    
    entryTimeChange: function(e) {
      this.labelChange('entry_time', e.detail.value) 
      this.setData({
        [`formData.entry_time`]:  e.detail.value,  
      })
    }, 
    isFirstChange: function(e) {
      this.setData({
        [`formData.is_first`]:  e.detail.value?1:0
      })
    }, 
   
    // 获取样板列表
    getTemplateList: function () {
        var __this = this;
        // 验证
        if ((this.data.templateList.length >= this.data.templateTotal) && this.data.templatePage > 0) {
            return false;
        }
        let search = [
          {field:'status',val:'1,2,3','operator':'RANGE'}
        ]
        // 发起请求
        var result = app.request_api('admin/template/index', {
            search :search,
            page: __this.data.templatePage + 1,
            quick_search: __this.data.templateKw,
            limit: 10,
        }, false);
        result.then(res => {  
            __this.setData({
                templateList: __this.data.templateList.concat(res.list),
                templatePage: this.data.templatePage + 1,
                templateTotal: res.total
            })
        });
    },

    // 搜索  
    halfBottomSearch: function (events) {
        var keywords = events.detail.value.trim();
        this.setData({
            templateKw: keywords,
            templateList: [],
            templatePage: 0,
            templateTotal: 0
        });
        this.getTemplateList();
    },

    // 选择样板
    chooseTemplateFun: function (events) {
        var index = events.currentTarget.dataset.index; 
        let chooseData = this.data.templateList[index]  
        let that = this
        // 请求接口 
        var result = app.request_api('admin/template/prePlanTemplate', {
          template_id:chooseData.template_id
        }, false, 'GET');
        result.then(res => {
          console.log('sxxx',res)
          let preOrder = res.pre_order
          let template = res.template
          if(preOrder != ''){
            // todo 判断 货号 输入状态

            that.setData({ 
              goodsNOTag : preOrder.goods_no?true:false,
              [`formData.template_id`]: preOrder.template_id,
              [`formData.goods_no`]: preOrder.goods_no || '',
              [`formData.goods_number`]: preOrder.goods_number || 0,

              [`formData.entry_time`]: preOrder.entry_time || '',
              [`formData.delivery_time`]: preOrder.delivery_time || '',
              [`formData.order_type`]: preOrder.order_type || 0,

              [`formData.time_cate_id`]: preOrder.time_cate_id || [], 
              [`formData.definition`]: preOrder.definition || [],
              [`formData.bd_id`]: preOrder.bd_id || [], // 波段 
    
              [`formData.cost`]: Number(preOrder.cost),
              [`formData.estimated_cost`]: Number(preOrder.estimated_cost),
              [`formData.sale_price`]: Number(preOrder.sale_price),
              [`formData.distribution_price`]: Number(preOrder.distribution_price), 
              
              [`formData.style_id`]: preOrder.style_id || 0,  // 一级风格 
              [`formData.gram_weight`]: preOrder.gram_weight || 0,
              [`formData.template_type`]: preOrder.template_type || '',
    
              [`formData.thickness`]: preOrder.thickness || '',
              [`formData.age_name`]: preOrder.age_name|| '',
              [`formData.faction_name`]: preOrder.faction_name|| '',
            
              [`formData.similar`]: preOrder.similar|| '',
              [`formData.fabric`]: preOrder.fabric|| '',
              [`formData.lining`]: preOrder.lining|| '',
              [`formData.filler`]: preOrder.filler|| '',
              [`formData.shipping_remark`]: preOrder.shipping_remark|| '',
              [`formData.window_level_remark`]: preOrder.window_level_remark|| '',
               
               
            }) 
          }else{ 
            if(template != ''){
            
            }
            
            that.setData({ 
              goodsNOTag :false,
              [`formData.goods_no`]: '',
              [`formData.goods_number`]:  0,
              [`formData.template_id`]: chooseData.template_id,
              [`formData.time_cate_id`]: chooseData.time_cate_id || [],
              [`formData.definition`]: chooseData.definition_id || [],
              [`formData.bd_id`]: chooseData.time_category_id || [], // 波段 
    
              [`formData.cost`]: Number(chooseData.template_cost),
              [`formData.estimated_cost`]: Number(chooseData.template_price),
              [`formData.sale_price`]: Number(chooseData.sale_price),
              [`formData.distribution_price`]: Number(chooseData.distribution_price), 
              
              [`formData.style_id`]: chooseData.style_id || 0,  // 一级风格 
              [`formData.gram_weight`]: chooseData.gram_weight || 0,
              [`formData.template_type`]: chooseData.template_type || '',
    
              [`formData.thickness`]: chooseData.thickness || '',
              [`formData.age_name`]: chooseData.age_name|| '',
              [`formData.faction_name`]: chooseData.faction_name|| '',
    
              [`formData.fabric`]: chooseData.fabric|| '',
              [`formData.lining`]: chooseData.lining|| '',
              [`formData.filler`]: chooseData.filler|| '',
              [`formData.shipping_remark`]: chooseData.shipping_remark|| '',
              [`formData.window_level_remark`]: chooseData.window_level_remark|| '',
              
            
            }) 
          }
          // this.labelChange('template_id', chooseData.template_id)
          this.initLabelItem(); // 必须在赋值之后调用 
        });

        that.setData({
          // 样板-标题（货号）
          chooseTemplate: chooseData.template_no?`${chooseData.template_name}(${chooseData.template_no})`:chooseData.template_name,
          templateData: chooseData, 
          [`sel_text.time_cate_name`]: chooseData.time_cate_name , // 二级时间分类（二级波段）
          [`sel_text.definition`]: chooseData.definition_name,  // 产品定义(二级风格) 
          [`sel_text.bd_name`]: chooseData.time_category_name ,  // 波段 
          [`sel_text.style_name`]: chooseData.style_name , // 一级风格  
        })  
    }, 
    // 删除选择项
    DeleteChoose: function (events) {
        var index = events.currentTarget.dataset.index; 
        this.setData({
            chooseTemplate: '',
            templateData: {},
            [`formData.template_id`]: 0
        });
    }, 
    // 关闭半屏
    close_half: function (e) {
        this.setData({
            is_show_shade: false,
            is_show_temp: false
        })
    }, 
    // 打开半屏
    open_half: function (e) {
        this.setData({
            is_show_shade: true,
            is_show_temp: true
        })
    }, 
    // 获取风格分类
    get_style_list: function () { 
        var result = app.request_api('admin/GoodsStyleCategory/getTreeAll', {}, false, 'GET');
        result.then(res => {
            this.setData({
              definition: [res, res[0].children],
              style_item: res,
              style_cate: res
            });
        });
    }, 
     
    // 获取时间分类（波段）
    get_time_cate: function () { 
        let result = app.request_api('admin/GoodsTimeCategory/getTreeAllV2', {
            
        }, false, 'GET');
        result.then(res => {  
            this.setData({
              time_cate_two: [res, res[0].children],
              bd_list: [res, res[0].children,res[0].children[0].children],
              time_cate_all: res 
            }); 
        });
    },   
  
    // 颜色列表
    get_color_list: function () { 
      let result = app.request_api('admin/color/allItem', { 
      }, false, 'GET');
      result.then(res => { 
          this.setData({ 
            color_list: res.list
          }); 
      });
  }, 

    // 二级时间分类-列变化时
    timeCateCloChange: function (e) { 
      let time_cate_all = this.data.time_cate_all;
      let time_cate_two = this.data.time_cate_two; 
      let tcIndex = this.data.sel_index.time_cate;
      var index = e.detail.value;  
      switch (e.detail.column) {
        case 0: // 一级分类改变时 
          time_cate_two[1] = time_cate_all[index].children; 
          tcIndex = [index, 0];
          break;
        case 1: // 二级分类改变时  
        tcIndex[1] = index; 
          break; 
        default: 
          break;
      }  
      // 重新渲染
      this.setData({
          time_cate_two: time_cate_two,
          [`sel_index.time_cate`]:tcIndex 
      });
   },
 
    // 二级时间分类-值变化时
    timeCateChange: function (e) { 
      let selectData = this.data.time_cate_two; 
      var selectArr = e.detail.value;  
       let time_cate_name = selectData[0][selectArr[0]].time_category_name + ' - ' + selectData[1][selectArr[1]].time_category_name ; 
      this.setData({
        [`formData.time_cate_id`] : [selectData[0][selectArr[0]].id, selectData[1][selectArr[1]].id], 
        [`sel_index.time_cate`]: selectArr,
        [`sel_text.time_cate_name`]: time_cate_name 
      });
      this.labelChange('time_cate_id', true) 
    },

  colorChange:function(e){
    let that = this
    let color_list = that.data.color_list; 
    let value = e.detail.value; 
    let colorData = color_list[value]  
    
    that.setData({  
      [`sel_text.color_name`]: colorData.name,
      [`formData.color_id`]: colorData.id,
      [`sel_index.color`]: value 
    }); 
    that.labelChange('color_id', true) 
    //  切换颜色，完善（深浅色）去匹配历史数据，获取颜色相关值
    let result = app.request_api('admin/PreProductPlan/getColorArr', { 
      color_id:that.data.formData.color_id,
      template_id:that.data.formData.template_id
    }, false, 'GET'); 
    result.then(res => {   
      // 没值，就清空，以免 使用者没注意修改，导致颜色填错
      that.setData({
        [`formData.uneven_color`]: res.uneven_color || '',
        [`formData.warm_color`]: res.warm_color || '',
        [`formData.color_system`]: res.color_system || '',
      }); 
      // 统计项
      that.labelChange('uneven_color', res.uneven_color) 
      that.labelChange('warm_color', res.warm_color) 
      that.labelChange('color_system', res.color_system) 

    });
  },

  
  // 产品定义-列变化时
  definitionCloChange: function (e) { 
    let style_cate = this.data.style_cate;
    let definition = this.data.definition; 
    let defIndex = this.data.sel_index.definition;
    let index = e.detail.value;   
    switch (e.detail.column) {
      case 0: // 一级改变时 
      definition[1] = style_cate[index].children; 
      defIndex = [index, 0];
        break;
      case 1: // 二级改变时  
      defIndex[1] = index; 
        break; 
      default: 
        break;
    }    
    this.setData({
      definition: definition,
      [`sel_index.definition`]:defIndex 
    });
  },
 
  // 产品定义-值变化时
  definitionChange: function (e) { 
    let selectData = this.data.definition; 
    var selectArr = e.detail.value;  
      let name = selectData[0][selectArr[0]].style_category_name + ' - ' + selectData[1][selectArr[1]].style_category_name ; 
    this.setData({
      [`formData.definition`]: [selectData[0][selectArr[0]].id, selectData[1][selectArr[1]].id], 
      [`sel_index.definition`]: selectArr,
      [`sel_text.definition`]: name
    });
    this.labelChange('definition', true) 
  },
  // 输入框改变
  formInputChange(e) {
    const {field} = e.currentTarget.dataset
    this.labelChange(field, e.detail.value.trim()) 
    this.setData({
      [`formData.${field}`]: e.detail.value.trim()
    });
  },
  // 公共下拉选择-改变
  formSelectChange(e) {
    const {field,da} = e.currentTarget.dataset
    let val =  this.data[`${da}`][e.detail.value].name 
    this.setData({
      [`formData.${field}`]: val
    }); 
    this.labelChange(field, true) 
  },

  // 仓库输入框改变
  stockInputChange(e) {
    const {field,index} = e.currentTarget.dataset
    let val = e.detail.value.trim()
    let stock_data = this.data.stock_data
    let reg = /^[0-9]\d*$/;
    if (reg.test(val) ){  
      stock_data[index][field] = parseInt(val);   
    } 
    this.setData({
      stock_data:stock_data
    });
    let stockTotal = this.calStockTotal(stock_data);
    this.labelChange('stock_data', stockTotal) 
  },

  stockBindfocus(e){
    const {field,index} = e.currentTarget.dataset
    let val = e.detail.value.trim()
    let stock_data = this.data.stock_data 
    let reg = /^[1-9]\d*$/; 
    if (!reg.test(val)){ 
      stock_data[index][field] = '';
      this.setData({
        stock_data:stock_data
      });
    } 
  },
  
  stockBindblur(e){
    const {field,index} = e.currentTarget.dataset
    let val = e.detail.value.trim()
    let stock_data = this.data.stock_data
    let reg = /^[1-9]\d*$/; 
    if (!reg.test(val)){
      stock_data[index][field] = 0;
      this.setData({
        stock_data:stock_data
      });
    } 
  },
  // 波段-列变化时
  bdCloChange: function (e) { 
    let time_cate_all = this.data.time_cate_all;
    let bd_list = this.data.bd_list; 
    let bdIndex = this.data.sel_index.bd;
    var index = e.detail.value;   
    switch (e.detail.column) {
      case 0: // 一级分类改变时 
      bd_list[1] = time_cate_all[index].children; 
      bd_list[2] = time_cate_all[index].children[0].children;
      bdIndex = [index, 0,0]; 
        break;
      case 1: // 二级分类改变时 
      bd_list[2] = bd_list[1][index].children; 
      bdIndex[1] = index
      bdIndex[2] = 0  
        break;
      case 2: // 三级分类改变时  
      bdIndex[2] = index;  
        break; 
      default: 
        break;
    }  
    this.setData({ 
      bd_list: bd_list,
      [`sel_index.bd`]:bdIndex 
    });
  },
 
  // 波段-值变化时 
  bdChange: function (e) { 
    let selectData = this.data.bd_list; 
    let selectArr = e.detail.value;  
    let name = selectData[0][selectArr[0]].time_category_name + ' - ' + selectData[1][selectArr[1]].time_category_name  + ' - ' + selectData[2][selectArr[2]].time_category_name ; 
    this.setData({
      [`formData.bd_id`] : [selectData[0][selectArr[0]].id, selectData[1][selectArr[1]].id, selectData[2][selectArr[2]].id], 
      [`sel_index.bd`]: selectArr,
      [`sel_text.bd_name`]: name 
    });
    this.labelChange('bd_id', true) 
  },
 
  styleChange:function(e){
    let style_item = this.data.style_item; 
    let value = e.detail.value; 
    let data = style_item[value]  
    this.setData({  
      [`sel_text.style_name`]: data.style_category_name,
      [`formData.style_id`]: data.id,
      [`sel_index.style_id`]: value 
    }); 
    this.labelChange('style_id', true) 
  },

   
  orderTypeChange:function(e){
    let item = this.data.order_type_list; 
    let value = e.detail.value; 
    let data = item[value]  
    console.log('orderTypeChange',data)
    this.setData({  
      [`sel_text.order_type`]: data.name,
      [`formData.order_type`]: data.value,
      [`sel_index.order_type`]: value 
    }); 
    this.labelChange('order_type', true) 
  },
      

    // 提交
    formSubmit: function (e) {
        var __this = this;
        if(!__this.data.formData.template_id){ 
          wx.showToast({
              title:'请选择模板',
              icon: 'none',
              duration: 2000,
          });
          return false;
        } 
        if(!__this.data.formData.color_id){ 
          wx.showToast({
              title:'颜色不能为空',
              icon: 'none',
              duration: 2000,
          });
          return false;
        }
        // 加载条
        wx.showLoading({
            title: '正在提交',
            mask: true
        }) 
        // 调用发布方法
        __this.form_submit_fun();
       
    },

    // 发起请求
    form_submit_fun: function () {
      let __this = this; 
      let req_param = __this.data.formData;
      req_param.stock_data = __this.data.stock_data;
      let req_url = 'admin/preProductPlan/add';
      if (__this.data.id > 0) {
          req_param.id = __this.data.id;
          req_url = 'admin/preProductPlan/edit';
      }
      // 发起请求
      let result = app.request_api(req_url, req_param, false);
      result.then(res => { 
         
          // 跳转回前一页
          wx.showModal({
              title: '提示',
              content: res.DiyApiMsg || '提交成功',
              showCancel: false,
              complete() {
                // 向上一级页面传递参数
                let eventChannel = __this.getOpenerEventChannel();
                console.log('eventChannel-aa-提交成功',eventChannel)
                if(eventChannel != undefined){
                   eventChannel.emit('changeData', {});
                }
                wx.navigateBack();
              }
          });
      });
      wx.hideLoading();
    }, 

})
